package main

import (
	"fmt"
	"io"
	"log"
	"net"
)

var connect = make([]net.Conn, 0)
var person = make(map[net.Conn]string)

func main() {
	listen, err := net.Listen("tcp", "0.0.0.0:8888")
	if err != nil {
		log.Fatal("fail to listen the connect!")
	}
	defer listen.Close()
	for {
		conn, err := listen.Accept()
		if err != nil {
			log.Fatal("faile to creat the connect!")

		}
		connect = append(connect, conn)
		fmt.Println(connect)
		go Process(conn)
	}
}
func Process(conn net.Conn) {
	bufs := make([]byte, 1024)
	n, err := conn.Read(bufs)
	if err != nil {
		if err == io.EOF {
			log.Fatal("客户端没有任何信息")
		}
		fmt.Println(err)
	}
	person[conn] = string(bufs[:n])
	fmt.Println(person)
	for {
		buf := make([]byte, 1024)
		n, err := conn.Read(buf)
		if err != nil {
			if err == io.EOF {
				log.Fatal("客户端没有任何信息")
			}
			return
		}
		fmt.Printf(string(buf[:n]) + "\n")
		if string(buf[:n]) == "quit" {
			_ = conn.Close()
			return
		} else if string(buf[:n]) == "private" {
			go pSendmsg(conn)
		}
		go sendMsg(conn, string(buf[:n]))
	}
}
func sendMsg(conn net.Conn, msg string) {
	var name string
	for k, v := range person {
		if k == conn {
			name = v
		}
	}
	for k, _ := range person {
		if k != conn {
			_, err := k.Write([]byte(name + "说:" + msg))
			fmt.Println(name + "说:" + msg)
			if err != nil {
				for i, v := range connect {
					if v == conn {
						connect[i] = nil
						person[conn] = ""
					}
				}
				fmt.Println(err)
			}
		}
	}

}
func pSendmsg(conn net.Conn) {
	var names, name, msg string
	fmt.Println("success")
	buf := make([]byte, 1024)
	n, err := conn.Read(buf)
	if err != nil {
		log.Fatal("faile to read!", err)
	}
	name = string(buf[:n])
	for {
		buf = make([]byte, 1024)
		n, err = conn.Read(buf)
		if err != nil {
			log.Fatal("faile to read!", err)
		}
		msg = string(buf[:n])
	for k, v := range person {
		if k == conn {
			names = v
		}
	}
	for k, v := range person {
		if name == v {
			_, err := k.Write([]byte(names + "偷偷告诉你:" + msg))
			if err != nil {
				_, err = conn.Write([]byte(name + "貌似没有上线哦"))
				if err != nil {
					fmt.Println(err)
				}
			}
		} else {
			_, err := k.Write([]byte("好像没有" + name + "这个人呢？在试下吧"))
			if err != nil {
				fmt.Println(err)
			}
		}
	}
	}
}
